package com.demo.crm.springboot3security.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.demo.crm.springboot3security.entity.FormTableStructure;
import com.demo.crm.springboot3security.mapper.FormTableStructureMapper;
import com.demo.crm.springboot3security.service.FormTableStructureService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;

@Service
public class FormTableStructureServiceImpl implements FormTableStructureService {

    @Autowired
    private FormTableStructureMapper formTableStructureMapper;

    @Override
    @Cacheable(value = "formTableStructure", key = "'formId:' + #formId + ':status:' + #status")
    public FormTableStructure findByFormIdAndStatus(Long formId, String status) {
        return formTableStructureMapper.findByFormIdAndStatus(formId, status);
    }

    @Override
    @Transactional
    @CacheEvict(value = "formTableStructure", allEntries = true)
    public FormTableStructure save(FormTableStructure structure) {
        if (structure.getId() == null) {
            structure.setCreatedAt(LocalDateTime.now());
            structure.setUpdatedAt(LocalDateTime.now());
            formTableStructureMapper.insert(structure);
        } else {
            structure.setUpdatedAt(LocalDateTime.now());
            formTableStructureMapper.update(structure);
        }
        return structure;
    }

    @Override
    @Transactional
    @CacheEvict(value = "formTableStructure", allEntries = true)
    public void delete(Long id) {
        formTableStructureMapper.deleteById(id);
    }

    @Override
    @Cacheable(value = "formTableStructure", key = "'id:' + #id")
    public FormTableStructure findById(Long id) {
        return formTableStructureMapper.selectOneById(id);
    }

    @Override
    @Cacheable(value = "formTableStructure", key = "'all'")
    public List<FormTableStructure> findAll() {
        return formTableStructureMapper.selectAll();
    }

    @Override
    @Cacheable(value = "formTableStructure", key = "'formId:' + #formId")
    public List<FormTableStructure> findByFormId(Long formId) {
        QueryWrapper query = QueryWrapper.create().where("form_id = ?", formId).orderBy("created_at desc");
        return formTableStructureMapper.selectListByQuery(query);
    }

    @Override
    public Page<FormTableStructure> findByPage(int pageNumber, int pageSize) {
        return formTableStructureMapper.paginate(pageNumber, pageSize, QueryWrapper.create());
    }

    @Override
    @Transactional
    @CacheEvict(value = "formTableStructure", allEntries = true)
    public void deleteByFormId(Long formId) {
        QueryWrapper query = QueryWrapper.create().where("form_id = ?", formId);
        formTableStructureMapper.deleteByQuery(query);
    }

    @Override
    @Transactional
    @CacheEvict(value = "formTableStructure", allEntries = true)
    public List<FormTableStructure> saveAll(List<FormTableStructure> structures) {
        LocalDateTime now = LocalDateTime.now();
        for (FormTableStructure structure : structures) {
            if (structure.getId() == null) {
                structure.setCreatedAt(now);
                structure.setUpdatedAt(now);
                formTableStructureMapper.insert(structure);
            } else {
                structure.setUpdatedAt(now);
                formTableStructureMapper.update(structure);
            }
        }
        return structures;
    }

    @Override
    @Cacheable(value = "formTableStructure", key = "'formId:' + #formId + ':latest'")
    public FormTableStructure findLatestByFormId(Long formId) {
        QueryWrapper query = QueryWrapper.create().where("form_id = ?", formId).orderBy("created_at desc").limit(1);
        return formTableStructureMapper.selectOneByQuery(query);
    }

    @Override
    @Transactional
    @CacheEvict(value = "formTableStructure", allEntries = true)
    public FormTableStructure activate(Long id) {
        FormTableStructure structure = findById(id);
        if (structure != null) {
            // 先将同一表单的其他结构设置为非激活
            QueryWrapper deactivateQuery = QueryWrapper.create().where("form_id = ?", structure.getFormId())
                    .and("status = ?", "active");
            FormTableStructure updateStructure = new FormTableStructure();
            updateStructure.setStatus("inactive");
            updateStructure.setUpdatedAt(LocalDateTime.now());
            formTableStructureMapper.updateByQuery(updateStructure, deactivateQuery);

            // 激活当前结构
            structure.setStatus("active");
            structure.setUpdatedAt(LocalDateTime.now());
            formTableStructureMapper.update(structure);
        }
        return structure;
    }

    @Override
    @Transactional
    @CacheEvict(value = "formTableStructure", allEntries = true)
    public FormTableStructure deactivate(Long id) {
        FormTableStructure structure = findById(id);
        if (structure != null) {
            structure.setStatus("inactive");
            structure.setUpdatedAt(LocalDateTime.now());
            formTableStructureMapper.update(structure);
        }
        return structure;
    }
}